package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.annotion.ActionExecOrder;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.util.*;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.workflow.model.*;
import com.ccp.dev.workflow.service.ActDefModelService;
import com.ccp.dev.workflow.service.BpmGangedSetService;
import com.ccp.dev.workflow.service.BpmNodeSetService;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * ClassDescribe:
 * 对象功能:联动设置表 控制器类
 * @author :fanruiqi
 */
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_WORKFLOW + "/bpmGangedSet")
@Controller
@Action(ownermodel = SysAuditModelType.PROCESS_MANAGEMENT)
public class BpmGangedSetController extends SysBaseController {
    private static final Logger logger = LoggerFactory.getLogger(BpmGangedSetService.class);

    @Resource
    private BpmGangedSetService bpmGangedSetService;
    @Resource
    private ActDefModelService actDefModelService;
    @Resource
    private BpmNodeSetService bpmNodeSetService;

    /**
     * 联动页面跳转
     * @param request
     * @param model
     * @return 跳转界面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX+UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "联动设置页面跳转",exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request,Model model){
        String modelId = RequestUtil.getString(request,"modelId");
        String parentProcDefId = RequestUtil.getString(request,"parentProcDefId");
        ActDefModel actDefModel = actDefModelService.getOneById(modelId);
        String procDefId = actDefModel.getProcDefId();
        String formKey = "";
        if (StringUtil.isEmpty(parentProcDefId)) {
            formKey= bpmNodeSetService.getFormKeyByProcDefId(procDefId);
        } else {
            formKey= bpmNodeSetService.getFormKeyByProcDefIdAndParent(procDefId, parentProcDefId);
        }
        //获取所有节点
        List<BpmNodeSet> nodeSetList = bpmNodeSetService.queryByProcDefId(procDefId);
        //获取绑定表单的过滤过的输入框（json字符串）
        String fields = "";
        String allFields = "";
        if (StringUtil.isNotEmpty(formKey)) {
            fields = bpmGangedSetService.getFieldsByFormkey(formKey,true);
            //获取绑定表单的所有类别的输入框（json字符串）
            allFields = bpmGangedSetService.getFieldsByFormkey(formKey,false);

        }

        model.addAttribute("modelId",modelId)
                .addAttribute("nodeSerList",nodeSetList)
                .addAttribute("formKey",formKey)
                .addAttribute("fields",fields)
                .addAttribute("allFields",allFields);
        return getAutoView();
    }

    /**
     * 获取页面列表数据
     * @param request
     * @return 返回结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "联动设置列表数据查询",detail="<#if success>联动设置列表数据查询成功</#if>")
    @ResponseBody
    public ResultData getList(HttpServletRequest request){
        String modelId = RequestUtil.getString(request,"modelId");
        try {
            List<BpmGangedSet> bpmGangedSetList = bpmGangedSetService.queryByModelId(modelId);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("query.success",bpmGangedSetList);
        }catch (Exception e){
            logger.error(e.getMessage());
            return getResultDataError("query.failure",1,e.getMessage());
        }
    }

    /**
     * 获取表字段
     * @param response
     * @return 返回数据
     */
    @RequestMapping("/getFields")
    @Action(description = "联动设置获取对应表的所有字段")
    @ResponseBody
    public String getFields(HttpServletRequest request, HttpServletResponse response)  {
        String formKey = RequestUtil.getString(request, "formKey");
        boolean isNeedFilter = RequestUtil.getBoolean(request, "isNeedFilter",false);
        String fields = bpmGangedSetService.getFieldsByFormkey(formKey,isNeedFilter);
        return fields;
    }

    /**
     * 保存流程联动设置
     * @param request
     * 参数格式如下：
     * json="[
     * {"id":"10000017830077","modelId":"10000016810272","nodeId":"1","nodeName":"起始节点","chooseField":[{"id":"10000017780058","name":"联动下拉框","key":"m:ce_cslcb:ldxlk","value":"下拉3"}],"changeField":[{"id":"10000013520045","name":"asd","key":"m:ce_cslcb:asd","type":"1","fieldtype":"0"}]}
     * ,{"id":"10000017830062","modelId":"10000016810272","nodeId":"2","nodeName":"所有节点","chooseField":[{"id":"10000017780060","name":"联动复选","key":"m:ce_cslcb:ldfx","value":"复选2"}],"changeField":[{"id":"10000017780058","name":"联动下拉框","key":"m:ce_cslcb:ldxlk","type":"8","fieldtype":"0","cascade":{"reduce":[{"id":"下拉2","name":"下拉22"}]}}]}
     * ,{"id":"0","modelId":"10000016810272","nodeId":"UserTask1","nodeName":"用户任务1","chooseField":[{"id":"10000017780059","name":"联动单选","key":"m:ce_cslcb:lddx","value":"单选1"}],"changeField":[{"id":"10000013520046","name":"zxc","key":"m:ce_cslcb:zxc","type":"1","fieldtype":"0"}]}
     *  ]"
     *  ,modelId="modelId"
     * @return 返回结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @Action(description = "保存流程联动设置",detail = "<#if success>流程联动设置保存成功</#if>")
    @ResponseBody
    public ResultData save(HttpServletRequest request){
      String json = RequestUtil.getString(request, "json");
      json = StringEscapeUtils.unescapeHtml4(json);
      String modelId = RequestUtil.getString(request, "modelId");
		try{
			bpmGangedSetService.batchSave(modelId,json);
			SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("save.success");
		}
		catch(Exception e){
            logger.error(e.getMessage());
            return getResultDataError("save.failure",1,e.getMessage());
		}
    }

    /**
     * 删除流程联动设置
     * @param request
     * @return 返回结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @Action(description = "删除流程联动设置",execOrder = ActionExecOrder.BEFORE,detail = "<#if success>流程联动设置删除成功</#if>")
    @ResponseBody
    public ResultData del(HttpServletRequest request){
        String[] ids = RequestUtil.getStringAryByStr(request,"ids");
        bpmGangedSetService.delByIdArray(ids);
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("delete.success");
    }

}